<script setup>
import { computed, onMounted, ref } from 'vue';

// 使用 import 加载图片
import markedImagePath from '@/assets/crazing_91_annotated.jpg';
import { useSystemStore } from '@/store/system';
import { ElPagination } from 'element-plus';
import * as XLSX from 'xlsx';
import { useModelStore } from '@/store/model'; // 引入模型状态管理
import { uploadImage as uploadImageApi } from '@/api/processApi'; // 引入新的上传图像 API

// 使用 Pinia store
const systemStore = useSystemStore();
const modelStore = useModelStore(); // 获取模型状态管理
const models = ref([]); // 用于存储模型配置

// 定义响应式数据
const isRunning = ref(false);
const progress = ref(0);
const defects = ref([]);
const markedImage = ref('');
const videoStream = ref(null); // 用于存储摄像头视频流
const uploadRecords = ref([]); // 用于存储上传记录
// 当前页码
const currentPage = ref(1);
const itemsPerPage = 5;

// 在组件挂载时不再获取模型列表
onMounted(() => {
  systemStore.fetchStatistics();
});

// 模拟开始运行的方法
async function startRunning() {
  // 检查模型是否为空，如果为空则设置为默认值
  if (!modelStore.config.name) {
    console.warn('模型名称为空，使用默认模型 test.pt');
    modelStore.config.name = 'test.pt'; // 设置默认模型
  }
  
  isRunning.value = true;
  progress.value = 0;
  // 上传所有记录的图片
  const filesToUpload = uploadRecords.value.map(record => record.file); // 收集所有文件
  try {
    const data = await uploadImageApi(filesToUpload, modelStore.config.name); // 使用新的 API
    console.log('上传成功:', data);
    // 处理返回的数据
    markedImage.value = data['Processed Images'][0].image; // 显示第一张处理后的图片
    defects.value = data['Detection Results'][0].detection_data; // 更新缺陷数据
    // 更新系统状态
    console.log('更新系统状态成功', defects.value);
    systemStore.totalCategories = data['total_classes'];
    systemStore.totalTargets = data['total_targets'];
  } catch (error) {
    console.error('上传图片失败:', error);
  }

  // 清空上传记录
  uploadRecords.value = [];

  const interval = setInterval(() => {
    if (progress.value < 100) {
      progress.value += 10;
    } else {
      clearInterval(interval);
      isRunning.value = false;
    }
  }, 500);
}

// 停止运行的方法
function stopRunning() {
  isRunning.value = false;
  progress.value = 0;
}

// 模拟获取缺陷数据的方法
function fetchDefectData() {
  setTimeout(() => {
    defects.value = [
      {
        id: 1,
        category: '裂纹',
        position: '左上',
        confidence: '95%',
        time: '0.5s',
      },
      {
        id: 2,
        category: '凹坑',
        position: '右下',
        confidence: '90%',
        time: '0.7s',
      },
      {
        id: 3,
        category: '划痕',
        position: '中间',
        confidence: '85%',
        time: '0.6s',
      },
      {
        id: 4,
        category: '腐蚀',
        position: '右上',
        confidence: '80%',
        time: '0.8s',
      },
      {
        id: 5,
        category: '变形',
        position: '左下',
        confidence: '75%',
        time: '0.9s',
      },
      {
        id: 6,
        category: '裂纹',
        position: '中下',
        confidence: '92%',
        time: '0.4s',
      },
    ];
    markedImage.value = markedImagePath; // 使用 import 的图片路径
  }, 1000);
}

// 计算当前页的数据
const paginatedDefects = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  console.log('当前页码:', defects.value.slice(start, start + itemsPerPage));
  return defects.value.slice(start, start + itemsPerPage);
});

// 计算总页数
const totalPages = computed(() =>
  Math.ceil(defects.value.length / itemsPerPage),
);

// 切换页码
function changePage(page) {
  if (page > 0 && page <= totalPages.value) {
    currentPage.value = page;
  }
}

// 导出数据为 XLS 文件
function exportToXLS() {
  const worksheet = XLSX.utils.json_to_sheet(defects.value);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Defects');
  XLSX.writeFile(workbook, 'defects.xlsx');
}

// 处理文件上传
function handleFileUpload(event) {
  const file = event.target.files[0];
  if (file) {
    console.log('Uploaded file:', file);
    uploadRecords.value.push({
      name: file.name,
      type: file.type,
      size: file.size,
      file: file, // 保存文件对象
    });
  }
}

// 打开摄像头
async function openCamera() {
  try {
    videoStream.value = await navigator.mediaDevices.getUserMedia({
      video: true,
    });
    const videoElement = document.querySelector('#cameraVideo');
    if (videoElement) {
      videoElement.srcObject = videoStream.value;
      videoElement.play();
    }
  } catch (error) {
    console.error('Error accessing camera:', error);
  }
}

// 关闭摄像头
function closeCamera() {
  if (videoStream.value) {
    const tracks = videoStream.value.getTracks();
    tracks.forEach((track) => track.stop());
    videoStream.value = null;
  }
}
</script>

<template>
  <div class="container mx-auto rounded-lg bg-gray-100 p-6 shadow-lg">
    <!-- 主容器 -->
    <div class="flex rounded-lg bg-white shadow-md">
      <!-- 左侧菜单 -->
      <div class="w-1/6 border-r border-gray-200 p-4">
        <!-- 其他选项 -->
        <div class="space-y-4">
          <div class="mb-2 text-lg font-semibold text-gray-800">
            请选择分类类型
          </div>
          <button
            @click="$refs.imageInput.click()"
            class="block w-full rounded-md border border-gray-300 bg-white text-left text-center text-lg text-gray-700 shadow-sm transition duration-300 ease-in-out hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            图片
          </button>
          <input
            type="file"
            ref="imageInput"
            accept="image/*"
            @change="handleFileUpload"
            class="hidden"
          />

          <button
            @click="$refs.videoInput.click()"
            class="block w-full rounded-md border border-gray-300 bg-white text-left text-center text-lg text-gray-700 shadow-sm transition duration-300 ease-in-out hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            视频
          </button>
          <input
            type="file"
            ref="videoInput"
            accept="video/*"
            @change="handleFileUpload"
            class="hidden"
          />

          <button
            @click="openCamera"
            class="block w-full rounded-md border border-gray-300 bg-white text-left text-center text-lg text-gray-700 shadow-sm transition duration-300 ease-in-out hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            摄像头
          </button>
          <button
            v-if="videoStream"
            @click="closeCamera"
            class="block w-full rounded-md border border-gray-300 bg-white text-left text-center text-lg text-gray-700 shadow-sm transition duration-300 ease-in-out hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-500"
          >
            关闭摄像头
          </button>
        </div>
      </div>

      <!-- 中间内容 -->
      <div class="w-5/6 p-6">
        <!-- 信息栏 -->
        <div class="mb-6 grid grid-cols-3 gap-6">
          <div class="rounded-lg bg-gray-50 p-4 text-center shadow-sm">
            <div class="text-lg font-medium text-gray-700">总类别数</div>
            <div class="text-2xl font-bold text-blue-600">
              {{ systemStore.totalCategories }}
            </div>
          </div>
          <div class="rounded-lg bg-gray-50 p-4 text-center shadow-sm">
            <div class="text-lg font-medium text-gray-700">总目标数</div>
            <div class="text-2xl font-bold text-blue-600">
              {{ systemStore.totalTargets }}
            </div>
          </div>
          <div class="rounded-lg bg-gray-50 p-4 text-center shadow-sm">
            <div class="text-lg font-medium text-gray-700">使用模型</div>
            <div class="text-xl font-bold text-blue-600">
              {{ systemStore.selectedModel }}
            </div>
          </div>
        </div>

        <!-- 标注图像 -->
        <div
          class="mb-6 flex h-64 items-center justify-center rounded-lg bg-gray-50 shadow-sm"
        >
          <img
            v-if="markedImage"
            :src="'data:image/jpeg;base64,' + markedImage"
            alt="Processed Image"
            class="h-full w-auto"
          />
          <span v-else class="text-gray-500">标注图像</span>
        </div>

        <!-- 摄像头视频 -->
        <div
          v-show="videoStream"
          class="mb-6 flex h-64 items-center justify-center rounded-lg bg-gray-50 shadow-sm"
        >
          <video id="cameraVideo" class="h-full w-auto" autoplay></video>
        </div>

        <!-- 上传记录 -->
        <div
          v-if="uploadRecords.length > 0"
          class="mb-6 rounded-lg bg-gray-50 p-4 shadow-sm"
        >
          <h3 class="mb-2 text-lg font-medium text-gray-700">上传记录</h3>
          <ul>
            <li
              v-for="(record, index) in uploadRecords"
              :key="index"
              class="text-gray-600"
            >
              {{ record.name }} ({{ record.type }},
              {{ (record.size / 1024).toFixed(2) }} KB)
            </li>
          </ul>
        </div>

        <!-- 表格 -->
        <div class="mb-6 rounded-lg bg-gray-50 p-4 shadow-sm">
          <div
            class="mb-2 grid grid-cols-6 border-b border-gray-200 pb-2 text-center"
          >
            <span>序号</span>
            <span>名称</span>
            <span>类别</span>
            <span>位置</span>
            <span>置信度</span>
            <span>用时</span>
          </div>
          <div
            v-if="paginatedDefects.length > 0"
            class="flex flex-col space-y-2"
          >
            <div
              v-for="defect in paginatedDefects"
              :key="defect.id"
              class="grid grid-cols-6 text-center"
            >
              <span>{{ defect.id }}</span>
              <span>{{ defect.filename }}</span>
              <span>{{ defect.category }}</span>
              <span>{{ defect.position }}</span>
              <span>{{ defect.confidence.toFixed(2) }}</span>
              <span>{{ defect.time.toFixed(2) }}ms</span>
            </div>
          </div>
          <div
            v-else
            class="flex h-32 items-center justify-center text-gray-500"
          >
            暂无数据
          </div>
        </div>

        <!-- 分页 -->
        <div class="mb-4 flex justify-center space-x-2">
          <ElPagination
            v-model="currentPage"
            :page-size="itemsPerPage"
            :total="defects.length"
            layout="prev, pager, next"
            @current-change="changePage"
          />
        </div>

        <!-- 操作按钮 -->
        <div class="flex items-center justify-between">
          <button
            @click="startRunning"
            class="rounded-lg bg-blue-500 px-4 py-2 text-white shadow transition duration-300 ease-in-out hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            开始运行
          </button>
          <button
            @click="exportToXLS"
            class="rounded-lg bg-blue-500 px-4 py-2 text-white shadow transition duration-300 ease-in-out hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            导出信息
          </button>
        </div>

        <!-- 进度条弹窗 -->
        <div
          v-if="isRunning"
          class="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50"
        >
          <div class="w-1/3 rounded-lg bg-white p-6 shadow-lg">
            <h2 class="mb-4 text-lg font-bold text-gray-800">运行中...</h2>
            <div class="mb-4 h-2.5 w-full rounded-full bg-gray-200">
              <div
                class="h-2.5 rounded-full bg-blue-600"
                :style="{ width: `${progress}%` }"
              ></div>
            </div>
            <div class="flex justify-end">
              <button
                @click="stopRunning"
                class="rounded-lg bg-red-500 px-4 py-2 text-white shadow transition duration-300 ease-in-out hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500"
              >
                终止
              </button>
              <button
                v-if="progress === 100"
                @click="isRunning = false"
                class="ml-2 rounded-lg bg-green-500 px-4 py-2 text-white shadow transition duration-300 ease-in-out hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 这里可以添加自定义样式 */
</style>
